package com.kwlt.smc.http;

import java.io.File;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kwlt.smc.entity.CallBox;
import com.kwlt.smc.entity.ErrorStatus;
import com.kwlt.smc.entity.HttpSmsEntity;
import com.kwlt.smc.entity.Returnsms;
import com.kwlt.smc.entity.StatusBox;
import com.kwlt.smc.util.ConUtils;
import com.kwlt.smc.util.SendHttpUtils;
import com.kwlt.smc.util.XmlHttpUtil;


public class Zb001Impl implements HttpSmsInter{

	public static Logger rptLog =  LoggerFactory.getLogger("zb001rpt");
	
	public static Logger mtLog =  LoggerFactory.getLogger("zb001mt");
	
	public static Logger moLog =  LoggerFactory.getLogger("zb001mo");
	/**
	 * 获取状态报告
	 */
	public void getHttpSmsRpt(HttpSmsEntity httpSmsEntity) {
		System.out.println(httpSmsEntity.getNumbers()+" rpt thread is run success!");
		Map<String, String> rptMap = getRptMap(httpSmsEntity);
		while(true){
			String rpt = SendHttpUtils.sendHttpPostRequest(httpSmsEntity.getRptUrl(), rptMap,"UTF-8");
			if(rpt!=null && !"".equals(rpt)){
				if(!XmlHttpUtil.isError(rpt)){
					List<StatusBox> list = XmlHttpUtil.getStatusBox(rpt);
					for(StatusBox box:list){
						//查找临时文件
						if(box!=null){
							File file = FileUtils.getFile(httpSmsEntity.getTmpPath()+box.getTaskid()+box.getMobile());
							if(file!=null){
								String localMsgId = getLocalMsgId(file);
								String rptValue = "";
								if("10".equals(box.getStatus())){
									rptValue = "DELIVRD";
								}else{
									rptValue = "Faild20";
								}
								createMobileRptFile(httpSmsEntity, box.getMobile(),rptValue, localMsgId, box.getTaskid(),file);
							}else{
								rptLog.info("not find tmp file:"+box.getMobile()+"\t"+box.getTaskid());
							}
						}
					}
				}else{
					ErrorStatus errorStatus = XmlHttpUtil.getErrorStatus(rpt);
					rptLog.info("查询状态报告异常||异常代码"+errorStatus.getError()+"\t"+errorStatus.getRemark());
				}
			}
			ConUtils.threadSleep(10000);
		}
	}

	/**
	 * 组装http发送map
	 * @param phone 手机号
	 * @param msg 发送内容
	 * @param httpSmsEntity 用户名和密码实体类
	 * @param expaCode 扩展码
	 * @return
	 */
	public Map<String,String> getSendMap(String phone,String msg,HttpSmsEntity httpSmsEntity,String expaCode){
		Map<String,String> map = new HashMap<String,String>();
		map.put("userid", httpSmsEntity.getUserId());
		map.put("account", httpSmsEntity.getUserName());
		map.put("password", httpSmsEntity.getPassword());
		map.put("mobile", phone);
		map.put("content", msg);
		map.put("action", "send");
		if(expaCode!=null && !"".equals(expaCode)){
			map.put("extno", expaCode);
		}
		return map;
	}
	/**
	 * 发送短信
	 */
	public void sendHttpSms(HttpSmsEntity httpSmsEntity) {
		System.out.println(httpSmsEntity.getNumbers()+ " mt thread is run success!");
		File mtFile = FileUtils.getFile(httpSmsEntity.getMtPath()+"1/");
		while(true){
			for(File file:mtFile.listFiles()){
				try {
					List<String> list = FileUtils.readLines(file, "GBK");
					if(list!=null && list.size()>0){
						String accessNumber = list.get(6);
						String phone = list.get(11);
						String localMsgId = list.get(18);
						String msg = list.get(20);
						//截取扩展码
						String expaCode = accessNumber.substring(httpSmsEntity.getAccessNumbers().length(),accessNumber.length());
						Map<String, String> sendMap = getSendMap(phone, msg, httpSmsEntity, expaCode);
						String request = SendHttpUtils.sendHttpPostRequest(httpSmsEntity.getSendUrl(), sendMap,"GB2312");
						Returnsms returnsms = XmlHttpUtil.getReturnsms(request);
						String log = "send http sms:"+phone+"\t"+accessNumber+"\t"+localMsgId+"\t"+msg+"\t"+returnsms.getReturnstatus()+"\t";
						log = log + returnsms.getMessage()+"\t"+returnsms.getRemainpoint()+"\t"+returnsms.getTaskID();
						mtLog.info(log);
						//如果返回大于0则代表提交成功
						//则将成功返回的消息ID和手机号作为文件名生成临时文件到临时目录,并且删除MT文件
						FileUtils.writeStringToFile(new File(httpSmsEntity.getTmpPath()+returnsms.getTaskID()+phone),localMsgId,"GBK");
						file.delete();
						if("Success".equals(returnsms.getReturnstatus()) && "0".equals(returnsms.getRemainpoint())){
							//如果余量为一条的时候，则停止发送
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ConUtils.threadSleep(1000);
		}
	}
	
	public String getLocalMsgId(File tmpFile){
		try {
			List<String> list = FileUtils.readLines(tmpFile, "GBK");
			if(list!=null && list.size()>0)
				return list.get(0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void createMobileRptFile(HttpSmsEntity httpSmsEntity,String phone,String rptValue,
			String localMsgId,String messageId,File tmpFile){
		StringBuffer rptFileCont = new StringBuffer();
		rptFileCont.append(messageId).append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append(phone).append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append("\n");
		rptFileCont.append(localMsgId).append("\n");
		rptFileCont.append("\n");//
		rptFileCont.append("RPT ").append(messageId+" ").append(rptValue).append("\n");
		rptFileCont.append("\n");
		try {
			FileUtils.writeStringToFile(new File(httpSmsEntity.getRptPath()+messageId+phone+ConUtils.formatseq()), 
					rptFileCont.toString(),"GBK");
			tmpFile.delete();
			rptLog.info("mobile rpt file message:"+phone+"\t"+localMsgId+"\t"+messageId+"\t"+rptValue);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 组装http获取状态报告map
	 * @param httpSmsEntity
	 * @return
	 */
	public Map<String,String> getRptMap(HttpSmsEntity httpSmsEntity){
		Map<String,String> map = new HashMap<String,String>();
		map.put("userid", httpSmsEntity.getUserId());
		map.put("account", httpSmsEntity.getUserName());
		map.put("password", httpSmsEntity.getPassword());
		map.put("action", "query");
		return map;
	}
	/**
	 * 获取mo
	 */
	public void getHttpSmsMo(HttpSmsEntity httpSmsEntity){
		System.out.println(httpSmsEntity.getNumbers()+ " mo thread is run success!");
		Map<String, String> rptMap = getRptMap(httpSmsEntity);
		while(true){
			String mo = SendHttpUtils.sendHttpPostRequest(httpSmsEntity.getMoUrl(), rptMap,"UTF-8");
			if(mo!=null && !"".equals(mo)){
				if(!XmlHttpUtil.isError(mo)){
					List<CallBox> callBoxList = XmlHttpUtil.getCallBox(mo);
					for(CallBox box:callBoxList){
						if(box!=null){
							createMoFile(httpSmsEntity, box.getMobile(), box.getContent(),
									box.getReceivetime(), "", box.getTaskid());
						}
					}
				}else{
					ErrorStatus errorStatus = XmlHttpUtil.getErrorStatus(mo);
					moLog.info("查询上行异常||异常代码"+errorStatus.getError()+"\t"+errorStatus.getRemark());
				}
			}
			ConUtils.threadSleep(6000);
		}
	}
	
	/**
	 * 创建Mo文件
	 * @param httpSmsEntity
	 * @param phone
	 * @param content
	 * @param date
	 * @param expaCode
	 * @param messageId
	 */
	public void createMoFile(HttpSmsEntity httpSmsEntity,String phone,String content
			,String date,String expaCode,String messageId){
		StringBuffer moFileCont = new StringBuffer();
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append(phone).append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append(httpSmsEntity.getAccessNumbers()+expaCode).append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append("\n");
		moFileCont.append(content).append("\n");
		try {
			FileUtils.writeStringToFile(new File(httpSmsEntity.getRptPath()+messageId+phone+ConUtils.formatseq()), 
					moFileCont.toString(),"GBK");
			moLog.info("mo file message:"+phone+"\t"+date+"\t"+messageId+"\t"+expaCode+"\t"+content);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
